<template>
  <div class="dynamic_form_item">
    <a-form-item :name="props.question.key">
      <template v-slot:label>
        <label for="">{{ props.question.label }}</label>
        <a-tooltip v-if="props.question.state.tipText" :key="props.question.label" :title="props.question.state.tipText">
          <i class="iconfont" :style="{ marginLeft: '8px' }" :class="props.question.state.tipIconClassName"></i>
        </a-tooltip>
      </template>
      <template v-if="props.config.isView">
        <span v-if="props.question.state.labelKey">{{ showKeyName(props.dataForm, props.question.state.labelKey) }}</span>
        <span v-else>{{ props.question.value }}</span>
      </template>
      <template v-else>
        <div class="dynamic_relateBtn">
          <a-select
            v-model:value="props.question.value"
            :mode="props.question.state.multiple ? 'tags' : ''"
            allowClear
            :disabled="props.question.disabled"
            :dropdownStyle="{ display: 'none' }"
            :placeholder="props.question.placeholder"
            :multiple="props.question.state.multiple ? true : false"
            :options="props.question.options"
            @click="selectId()"
          >
          </a-select>
        </div>
      </template>
    </a-form-item>
  </div>
</template>
<script setup lang="ts">
import { watch, getCurrentInstance, onMounted, onUnmounted, reactive, ref } from 'vue';
import { QuestionBase } from '../../../question-base';
import { filter } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { DYNAMICLAYERTABLE, DYNAMICLAYERTABLEDATA, INFOSERVE } from '@/mixins/subject/subject-types';
import { showKeyName } from '../../../../publicMethod';

//subject变量
let $subscribeSub: Subscription;
let $subscribeSubLayer: Subscription;
let seleceData: any = ref([]);

const { proxy }: any = getCurrentInstance();
let props = defineProps<{ question: QuestionBase<any>; formData: any; config: any; dataForm: any }>();
const emit = defineEmits(['update:formData']);
watch(
  () => props.question.value,
  (val) => {
    emit('update:formData', val);
    if ((!val || !val.length) && !seleceData.value.length) {
      seleceData.value = [];
    }
  },
  { flush: 'sync' }
);

watch(
  () => seleceData.value,
  (val) => {
    if (((val && !val.length) || !val) && props.question.value) {
      props.question.value = Array.isArray(props.question.value) ? [] : null;
    }
  },
  { flush: 'sync' }
);

onMounted(() => {
  subWatch();
});

//动态table弹层
const selectId = () => {
  proxy.$NotificationPubSub.pushParams({
    key: DYNAMICLAYERTABLE,
    value: {
      config: props.question.state.config,
      tables: props.question.state.table,
      form: props.question.state.form,
      index: props.question.state.index || 0,
      name: props.question.state.name || props.question.state.config.name || '',
      defaultValue: props.question.value
    }
  });
};

//格式化数据
const setData = (selectList: any) => {
  props.question.options = selectList.map((res: any) => ({
    value: res[props.question.state.keyValue || 'id'],
    label: res[props.question.state.keyName || 'name']
  }));
  if (props.question.state.multiple) {
    props.question.value = props.question.options.map((res: any) => res.value);
  } else {
    props.question.value = props.question.options[0].value;
  }
  if (props.question.state.labelKey && props.dataForm[props.question.state.labelKey]) {
    seleceData.value = Array.isArray(props.dataForm[props.question.state.labelKey]) ? props.dataForm[props.question.state.labelKey] : [props.dataForm[props.question.state.labelKey]];
  } else {
    seleceData.value = props.question.options.map((res: any) => res['label']);
  }
  console.log('sdw', props.question.value, seleceData.value);
};

//监听动态表单数据完成
const subWatch = () => {
  $subscribeSub = proxy.$NotificationFormSub
    .getParams()
    .pipe(filter((res: any) => res !== 0))
    .subscribe((item: any) => {
      if (item.key === INFOSERVE) {
        try {
          // 处理后台返回null 下拉框显示异常
          if (props.question.state?.multiple) {
            if (!props.question.value) {
              // eslint-disable-next-line vue/no-mutating-props
              props.question.value = [];
            }
          }
          // props.question.options = props.question.value;
          if (props.question.state.labelKey && showKeyName(item.value, props.question.state.labelKey)) {
            seleceData.value = [showKeyName(item.value, props.question.state.labelKey)];
            if (props.question.state.labelKey.includes('.')) {
              let keys: any = props.question.state.labelKey.split('.');
              if (item.value[keys[0]]) {
                const data = item.value[keys[0]];
                if (props.question.state?.multiple) {
                  let labelList = Array.isArray(data?.[keys[1]]) ? data?.[keys[1]] : data?.[keys[1]].split(',');
                  // eslint-disable-next-line vue/no-mutating-props
                  props.question.options = data?.[props.question.state.name]?.map((option: any, index: string | number) => {
                    return {
                      label: labelList?.[index],
                      value: option
                    };
                  });
                } else {
                  // eslint-disable-next-line vue/no-mutating-props
                  props.question.options = [
                    {
                      label: data?.[keys[1]],
                      value: data?.[props.question.state.name]
                    }
                  ];
                }
              }
            }
            if (props.question.state?.multiple) {
              console.log(props, '', item.value);
            }
          } else {
            seleceData.value = props.question.value.map((res: any) => res[props.question.state.keyName]);
          }
        } catch (error) {}
        //数据都全部都到了
      }
    });
  //接收数据
  $subscribeSubLayer = proxy.$NotificationPubSub
    .getParams()
    .pipe(filter((res) => res !== 0))
    .subscribe((item: any) => {
      try {
        if (item.key === DYNAMICLAYERTABLEDATA && item.value.name === props.question.state.name) {
          console.log('选中的值', item);
          setData(item.value.data);
        }
      } catch (error) {}
    });
};

//解绑
onUnmounted(() => {
  if ($subscribeSub != undefined) {
    $subscribeSub.unsubscribe();
    proxy.$NotificationFormSub.clearParams();
  }
  if ($subscribeSubLayer != undefined) {
    $subscribeSubLayer.unsubscribe();
    proxy.$NotificationPubSub.clearParams();
  }
});
</script>

<style lang="less" scoped>
@import url('./input-relateBtn.component.less');
</style>
